package com.jsn.hello_cmake.audio

import android.content.Context
import android.media.*
import android.media.AudioAttributes.USAGE_MEDIA
import android.media.AudioFormat.ENCODING_PCM_16BIT
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.jsn.hello_cmake.R
import kotlinx.android.synthetic.main.activity_audio.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.nio.ByteBuffer

class AudioActivity:AppCompatActivity() {

    val file= File(Environment.getExternalStorageDirectory(),"recording.pcm")

    val coroutineScope= CoroutineScope(Dispatchers.Main)
    // var fileh :File?=null

    val sample_rate=44100

    val channel_config= AudioFormat.CHANNEL_IN_MONO

    val audio_format= AudioFormat.ENCODING_PCM_16BIT

    val buffer_size_factor=2

    val buffer_size= AudioRecord.getMinBufferSize(sample_rate,channel_config,audio_format) *buffer_size_factor

    lateinit var audioManager:AudioManager


    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio)
        audioManager= getSystemService(Context.AUDIO_SERVICE) as AudioManager

        val audioTrack=AudioTrack(AudioAttributes.Builder().setUsage(USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).
            setLegacyStreamType(AudioManager.STREAM_MUSIC).build(),
            AudioFormat.Builder().setSampleRate(sample_rate).setEncoding(ENCODING_PCM_16BIT)
                .build(),
            buffer_size,
            AudioTrack.MODE_STREAM,
            audioManager.generateAudioSessionId())

        bt.setOnClickListener{
            coroutineScope.launch {
                withContext(Dispatchers.IO){
                    val fileInputStream=FileInputStream(file)
                    val buffer:ByteBuffer= ByteBuffer.allocateDirect(buffer_size)
                    audioTrack.play()
                    var i=fileInputStream.read(buffer.array())
                    while (i!=-1){
                        audioTrack.write(buffer,0,i)
                        i=fileInputStream.read(buffer.array())
                    }
                }
            }
        }
    }
}